﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Net;
using System.Management;

namespace HostProfiles
{
    public partial class FormMain : Form
    {
        string basePath = AppDomain.CurrentDomain.BaseDirectory + "\\Profiles\\";
        string hostPath = Environment.GetFolderPath(Environment.SpecialFolder.System) + "\\drivers\\etc\\hosts";
        Font baseFont;
        Font boldFont;
        int lastIndex = -1;
        bool goodbye = false;

        public FormMain()
        {
            InitializeComponent();
            baseFont = this.Font;
            boldFont = new Font(baseFont, FontStyle.Bold);
        }

        #region Froms

        private void FormMain_Load(object sender, EventArgs e)
        {
            if (!Directory.Exists(basePath))
            {
                Directory.CreateDirectory(basePath);
            }

            LoadIP();
            LoadProfiles();
        }

        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = !goodbye;
            HideShow();
        } 
        #endregion

        #region Buttons
        private void ButtonAdd_Click(object sender, EventArgs e)
        {
            AddProfile(TextBoxName.Text);
        }
        private void ButtonApply_Click(object sender, EventArgs e)
        {
            if (ListViewProfiles.SelectedItems.Count == 0)
            {
                return;
            }

            ApplyProfile();
        }
        private void ButtonFlushDNS_Click(object sender, EventArgs e)
        {
            FlushDNS();
        }
        private void ButtonAbout_Click(object sender, EventArgs e)
        {
            ShowAbout();
        }
        private void ButtonExit_Click(object sender, EventArgs e)
        {
            Exit();
        }
        
        #endregion

        #region Other Controls
        private void TextBoxProfile_TextChanged(object sender, EventArgs e)
        {
            LabelStatus.Text = "";
            ProgressBar.Value = 0;
            ButtonApply.Enabled = true;
            if (ListViewProfiles.SelectedItems.Count == 0) return;
            else
            {
                ListViewProfiles.SelectedItems[0].Tag = TextBoxProfile.Text;
                File.WriteAllText(ListViewProfiles.SelectedItems[0].SubItems[1].Text,
                    ListViewProfiles.SelectedItems[0].Tag.ToString());

            }
        }

        private void ListViewProfiles_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ListViewProfiles.SelectedItems.Count == 0)
            {
                return;
            }

            if (lastIndex == -1)
            {

                TextBoxProfile.Text = ListViewProfiles.SelectedItems[0].Tag.ToString();
                lastIndex = ListViewProfiles.SelectedItems[0].Index;
            }
            else if (lastIndex != ListViewProfiles.SelectedItems[0].Index)
            {
                TextBoxProfile.Text = ListViewProfiles.SelectedItems[0].Tag.ToString();
                lastIndex = ListViewProfiles.SelectedItems[0].Index;
            }


        }

        private void tabPageCurrent_Click(object sender, EventArgs e)
        {
        }

        private void tabControlMain_SelectedIndexChanged(object sender, EventArgs e)
        {
            TextBoxHost.Text = File.ReadAllText(hostPath);
            LoadIP();
        }

        #endregion

        #region BackgroundWorker
        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                backgroundWorker.ReportProgress(0);

                DirectoryInfo di = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.System));
                string pathIpconfig = basePath + "ipconfig.exe";//di.Parent.FullName + "\\prefetch\\ipconfig.exe";
                backgroundWorker.ReportProgress(10);
                ProcessStartInfo ps = new ProcessStartInfo(pathIpconfig, "/flushdns");
                ps.CreateNoWindow = true;
                ps.WindowStyle = ProcessWindowStyle.Hidden;
                backgroundWorker.ReportProgress(50);
                Process.Start(ps);

            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }

            backgroundWorker.ReportProgress(100);

        }

        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            ToolStripTop.Enabled = true;
            LabelStatus.Text = "DNS has been flushed!";
            contextMenuStripProfiles.Enabled = true;
        }

        private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            ProgressBar.Value = e.ProgressPercentage;
        }
        
        #endregion

        #region Menu
        private void applyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ButtonApply_Click(this, e);
        }

        private void removeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ListViewProfiles.SelectedItems.Count == 0)
            {
                return;
            }
            if (MessageBox.Show("Remove profile: " + ListViewProfiles.SelectedItems[0].Text + " ?",
                "Confirm", MessageBoxButtons.YesNo)
                == DialogResult.Yes)
            {
                try
                {
                    File.Delete(ListViewProfiles.SelectedItems[0].SubItems[1].Text);
                    ListViewProfiles.Items.Remove(ListViewProfiles.SelectedItems[0]);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                }
            }
        }

        private void NotifyIconProfiles_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            HideShow();
        }

        private void showToolStripMenuItem_Click(object sender, EventArgs e)
        {
            HideShow();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowAbout();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Exit();
        }


        private void flushDNSToolStripMenuItemSystem_Click(object sender, EventArgs e)
        {
            FlushDNS();
        }

        private void flushDNSToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FlushDNS();
        }

        void menu_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem menu = sender as ToolStripMenuItem;
            if (menu.Tag != null)
            {
                ListViewItem lv = menu.Tag as ListViewItem;
                lv.Selected = true;
                ApplyProfile();

            }
        }

        #endregion

        #region Private Methods
        private void LoadIP()
        {
            TextBoxIPs.Clear();
            //IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
            //foreach (var item in ips)
            //{
            //    byte[] bs= item.GetAddressBytes();
            //    TextBoxIPs.AppendText(bs[0] + "." + bs[1] + "." + bs[2] + "." + bs[3]+"\r\n");
            //}
            ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection queryCollection = query.Get();
            foreach (ManagementObject mo in queryCollection)
            {
                if (mo["IPEnabled"].ToString() == "True")
                {
                    //foreach (var item in mo.Properties)
                    //{
                    //    Debug.WriteLine(item.Name + "=" + item.Value);
                    //}
                    TextBoxIPs.AppendText("Mac Description: " + mo["Description"] + "\r\n");
                    TextBoxIPs.AppendText("Mac Address: " + mo["MacAddress"].ToString() + "\r\n");
                    ExtractStringArray(mo, "IPAddress", "IP Address", false);
                    ExtractStringArray(mo, "IPSubnet", "Subnet", true);
                    ExtractStringArray(mo, "DefaultIPGateway", "Gateway", true);
                    ExtractStringArray(mo, "DNSServerSearchOrder", "DNS Server", false);

                    //IPSubnet=System.String[]

                }
            }
        }

        private void ExtractStringArray(ManagementObject mo, string prop, string name, bool first)
        {
            string[] dnsOrder = (string[])mo[prop];
            TextBoxIPs.AppendText(name + ": ");
            if (!first) TextBoxIPs.AppendText("\r\n");
            foreach (var at in dnsOrder)
            {
                TextBoxIPs.AppendText(at + "\r\n");
                if (first) break;
            }
        }

        private void LoadProfiles()
        {
            ListViewProfiles.Items.Clear();
            string hosts = File.ReadAllText(hostPath);
            string[] files = Directory.GetFiles(basePath, "*.txt");
            foreach (var file in files)
            {
                AddProfile(hosts, file);
            }
        }

        private void AddProfile(string hosts, string file)
        {
            FileInfo fi = new FileInfo(file);
            string[] info = new string[] { fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length), fi.FullName };
            ListViewItem lv = new ListViewItem(info);
            lv.Tag = File.ReadAllText(fi.FullName);

            ToolStripMenuItem menu = new ToolStripMenuItem(info[0])
            {
                Tag = lv,

            };
            menu.Click += new EventHandler(menu_Click);
            if (lv.Tag.ToString() == hosts)
            {
                lv.Font = boldFont;
                menu.Font = boldFont;
                menu.Image = imageList1.Images[1];
                lv.ImageIndex = 1;

            }
            else
            {
                lv.ImageIndex = 0;
                menu.Image = imageList1.Images[0];

            }
            ListViewProfiles.Items.Add(lv);
            switchProfilesToolStripMenuItem.DropDownItems.Add(menu);


        }

        private void AddProfile(string name)
        {
            if (string.IsNullOrEmpty(name)) return;
            string file = basePath + name + ".txt";
            try
            {
                if (File.Exists(file))
                {
                    MessageBox.Show("Profile already exist!");
                }
                else
                {
                    File.WriteAllText(file, "");
                    AddProfile(null, file);
                    ListViewProfiles.Items[ListViewProfiles.Items.Count - 1].Selected = true;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }

        private void ApplyProfile()
        {
            //foreach (ListViewItem item in ListViewProfiles.Items)
            //{
            //    if (item == ListViewProfiles.SelectedItems[0])
            //    {
            //        item.Font = boldFont;
            //    }
            //    else
            //    {
            //        item.Font = baseFont;
            //    }
            //}

            foreach (ToolStripMenuItem item in switchProfilesToolStripMenuItem.DropDownItems)
            {
                if (item.Tag != null)
                {
                    ListViewItem lv = item.Tag as ListViewItem;
                    if (lv == ListViewProfiles.SelectedItems[0])
                    {
                        lv.Font = boldFont;
                        lv.ImageIndex = 1;
                        item.Font = boldFont;
                        item.Image = imageList1.Images[1];
                    }
                    else
                    {
                        lv.ImageIndex = 0;
                        lv.Font = baseFont;
                        item.Font = baseFont;
                        item.Image = imageList1.Images[0];
                    }
                }
            }

            File.WriteAllText(hostPath, ListViewProfiles.SelectedItems[0].Tag.ToString());

            FlushDNS();

            ButtonApply.Enabled = false;
        }

        private void FlushDNS()
        {
            LabelStatus.Text = "Flushing DNS...";
            ToolStripTop.Enabled = false;
            contextMenuStripProfiles.Enabled = false;
            backgroundWorker.RunWorkerAsync();
        }


        private void ShowAbout()
        {
            FormAbout about = new FormAbout();
            about.ShowDialog();
        }

        private void HideShow()
        {
            if (this.Visible)
            {
                this.Hide();
                showToolStripMenuItem.Text = "&Show";
            }
            else
            {
                this.Show();
                showToolStripMenuItem.Text = "&Hide";
            }
        }

        private void Exit()
        {
            goodbye = true;
            Application.Exit();
        }

        #endregion

    }
}
